<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8"/>
  <title>Demo: Flexible Grid Layout &ndash; YAML CSS Framework</title>

  <!-- Mobile viewport optimisation -->
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <link href="./css/youobserve/flexible-grids.css" rel="stylesheet" type="text/css"/>
  <!--[if lte IE 7]>
  <link href="./library/yaml4/core/iehacks.css" rel="stylesheet" type="text/css" />
  <![endif]-->

  <!--[if lt IE 9]>
  <script src="./library/yaml4/lib/html5shiv/html5shiv.js"></script>
  <![endif]-->

  <link rel="stylesheet" type="text/css" media="screen" href="library/jqgrid/css/ui.jqgrid.css" />
  <link rel="stylesheet" type="text/css" media="screen" href="library/jqgrid/plugins/ui.multiselect.css" />
  <script type="text/javascript" src='http://maps.google.com/maps/api/js?sensor=false'></script>

  <!-- include proj4fs to transform -->
  <script src="library/proj4js/lib/proj4js-compressed.js" type="text/javascript"></script>
  <script src="library/proj4js/lib/defs/EPSG900913.js" type="text/javascript"></script>

  <link rel="stylesheet" href="library/OpenLayers/theme/default/style.css" type="text/css" />

  <link rel="stylesheet" type="text/css" media="screen" href="css/youobserve/index_map.css" />


  <link type="text/css" href="library/jquery-ui-1.10.4/development-bundle/themes/cupertino/jquery-ui.css" rel="stylesheet" />
  <script type="text/javascript" src="library/OpenLayers/OpenLayers.js"></script>

  <script type="text/javascript" src="library/jquery/jquery-1.11.0.min.js"></script>

  <script type="text/javascript" src="library/jquery-ui-1.10.4/development-bundle/external/jquery.bgiframe.js"></script>
  <script type="text/javascript" src="library/jquery-ui-1.10.4/development-bundle/ui/jquery.ui.core.js"></script>
  <script type="text/javascript" src="library/jquery-ui-1.10.4/development-bundle/ui/jquery.ui.widget.js"></script>
  <script type="text/javascript" src="library/jquery-ui-1.10.4/development-bundle/ui/jquery.ui.datepicker.js"></script>
  <script type="text/javascript" src="library/jquery-ui-1.10.4/development-bundle/ui/jquery.ui.mouse.js"></script>
  <script type="text/javascript" src="library/jquery-ui-1.10.4/development-bundle/ui/jquery.ui.button.js"></script>
  <script type="text/javascript" src="library/jquery-ui-1.10.4/development-bundle/ui/jquery.ui.draggable.js"></script>
  <script type="text/javascript" src="library/jquery-ui-1.10.4/development-bundle/ui/jquery.ui.position.js"></script>
  <script type="text/javascript" src="library/jquery-ui-1.10.4/development-bundle/ui/jquery.ui.resizable.js"></script>
  <script type="text/javascript" src="library/jquery-ui-1.10.4/development-bundle/ui/jquery.ui.dialog.js"></script>
  <script type="text/javascript" src="library/jquery-ui-1.10.4/development-bundle/ui/jquery.ui.tabs.js"></script>

  <script src="library/jqgrid/js/i18n/grid.locale-en.js" type="text/javascript"></script>
  <script src="library/jqgrid/js/jquery.jqGrid.min.js" type="text/javascript"></script>

  <script src="library/colorbox-master/jquery.colorbox.js"></script>
  <link rel="stylesheet" href="library/colorbox-master/example1/colorbox.css" />

<script type="text/javascript">

/*** see: ECMA-262 5th Edition / December 2009 ***/
"use strict";

/**********************************************************************************************

  The javascipt code is split in 3 parts:

  1. external javascript libraries (jquery, jquery-ui, openlayers, proj4js)
  2. jquery code which handles events. It starts some where at line 640 in the ready function.
  3. code that is mostly related to openlayers map actions and it is encapsulated in
     a function called "geocontexter" (line 78). This function is based on the module pattern.
     The first goal wasnt to build a javascript module but to encapsulate
     its code to prevent conflicts with other libraries.

***********************************************************************************************/

/**
 * Public methods:
 * init()                     // main init method which is called once from body onload
 * toggleControl()            // switch between map controls, called from the top right radio buttons
 * showRightColumn()
 * hideRightColumn()
 * showResult()               // show result species
 * showMessage()
 * addRecordsVectorLayers()   // push species observations in map
 * removeObservationsLayer()
 * showSpeciesDetails()
 * transformBufferSize()
 * desactivateDrawControl()
 * EPSG_4326_geom_string()
 * EPSG_4326_geom()
 * geometry_type()
 *
 *
 */

var geocontexter = function () {

    /* openlayers map object */
    var map;

    /* array that contains draw features like point, line and polygon  */
    var drawControls = null;

    /* selected vector geometry to get results from */
    var EPSG_4326_geom_string;

    var featureLayer  = null;
    var selectFeature = null;
    var observationShapeLayer;

    /* species name */

    var species_name;

    /* centroid of the selected vector geometry to get results from */

    var selected_centroid;

    /* selected vector geometry in "EPSG:4326" */

    var EPSG_4326_geom = null;

    /* select vector geometry type; point, linestring or polygon */

    var geometry_type = null;

    var running_action = false;

    var highlight_flag = false;

    /* object with id_record's as keys and OpenLayers_Layer_Vector_ID's as values.
       it describes the relations between observations vectors and observation record ids.
       it is used to highlight an observation vector when click on an observation in the result table
    */
    var point_obs_relation = {};

    /* it contains an OpenLayers_Layer_Vector_ID when the related vector is highlighted in the map */
    var highlighted_OpenLayers_Layer_Vector_ID = false;

    /*--------------------------------------------------------*/
    /* push drawed observation shape in map as feature vector */
    /*--------------------------------------------------------*/

    var showObservationShape = function (geom) {

        var shapeStyles = new OpenLayers.StyleMap( {
            "default": new OpenLayers.Style( {
                pointRadius: "6",
                fillColor: "#ffffff",
                fillOpacity: 0.25,
                strokeColor: "#ffffff",
                strokeWidth: 4,
                strokeOpacity: 0.8,
                graphicZIndex: 1
            }),
            "select": new OpenLayers.Style({
                pointRadius: "4",
                fillColor: "#0000ff",
                fillOpacity: 0.3,
                strokeColor: "#0000ff",
                strokeWidth: 3,
                strokeOpacity: 0,
                graphicZIndex: 2
            })
        });

        if (observationShapeLayer) {
            map.removeLayer(observationShapeLayer);
        }

        observationShapeLayer = new OpenLayers.Layer.Vector(
            "Observation shape",
            {
                styleMap: shapeStyles,
                rendererOptions: {zIndexing: true}
            }
        );

        map.addLayer(observationShapeLayer);

        var feature = new OpenLayers.Feature.Vector(
            geom.transform( new OpenLayers.Projection("EPSG:4326"),
                            new OpenLayers.Projection("EPSG:900913")
            )
        );

        observationShapeLayer.addFeatures([feature]);
    };

    /*----------------------------------------------------------------*/
    /* desactivate draw feature and switch to navigation control mode */
    /*----------------------------------------------------------------*/

    var desactivateDrawControl = function () {
        /* IE get an error whitout this check */
        if (drawControls !== null) {
            var pointControl   = drawControls.point;
            var lineControl    = drawControls.line;
            var polygonControl = drawControls.polygon;

            pointControl.deactivate();
            lineControl.deactivate();
            polygonControl.deactivate();
        }

        /* select navigate check box  */
        $("#noneToggle").attr("selected", "selected");
    };

    /*---------------------------------------------------------------------*/
    /* callback function after drawing a point, line or polygon in the map */
    /*---------------------------------------------------------------------*/

    var done = function (geom) {
        selected_centroid = geom.getCentroid();

        EPSG_4326_geom = geom.transform(new OpenLayers.Projection("EPSG:900913"),
                                        new OpenLayers.Projection("EPSG:4326"));

        EPSG_4326_geom_string = EPSG_4326_geom.toString();

        showObservationShape(geom);
        desactivateDrawControl();
    };

    var done_point = function (geom) {
        geometry_type = 'point';
        done(geom);
    };

    var done_line = function (geom) {
        geometry_type = 'line';
        done(geom);
    };

    var done_polygon = function (geom) {
        geometry_type = 'polygon';
        done(geom);
    };

    /*--------------------------------------------------------------*/
    /* add draw feature to create vector shapes to get observations */
    /*--------------------------------------------------------------*/

    var add_draw_feature = function () {
        var selectionLayer = new OpenLayers.Layer.Vector("Seletion Layer");

        map.addLayers([selectionLayer]);

        /* the callback of each draw feature triggers an observation search  */

        drawControls = {
            point: new OpenLayers.Control.DrawFeature(selectionLayer, OpenLayers.Handler.Point,
                                                      {
                                                         callbacks:{done: done_point}
                                                      }),

            line: new OpenLayers.Control.DrawFeature(selectionLayer, OpenLayers.Handler.Path,
                                                     {
                                                        callbacks:{done: done_line}
                                                     }),

            polygon: new OpenLayers.Control.DrawFeature(selectionLayer, OpenLayers.Handler.Polygon,
                                                        {
                                                           callbacks:{done: done_polygon}
                                                        })
        };

        for(var key in drawControls) {
            if (drawControls.hasOwnProperty(key)) {
                map.addControl(drawControls[key]);
            }
        }
    };

    /*-------------------------------------------------------*/
    /* init of openlayers. it is called from the body onload */
    /*-------------------------------------------------------*/
    var openlayers_init = function () {
        OpenLayers.DOTS_PER_INCH = 72;
        map = new OpenLayers.Map('map', {
                projection:         "EPSG:4326",
                displayProjection:  "EPSG:4326",
                fractionalZoom: true
              });

        var ghyb = new OpenLayers.Layer.Google(
            "Google Hybrid",
            {type: google.maps.MapTypeId.HYBRID}
        );

        var gsat = new OpenLayers.Layer.Google(
            "Google Satellite",
            {type: google.maps.MapTypeId.SATELLITE}
        );

        map.addLayers([ghyb, gsat]);

      /*----------------------------------------------------*/
      /* deselect draw feature if zooming/moving in the map */
      /*----------------------------------------------------*/

        map.events.register(
            'moveend',
            null,
            function () {
                desactivateDrawControl();
            }
        );

        map.addControl(new OpenLayers.Control.MousePosition());
        map.addControl(new OpenLayers.Control.LayerSwitcher());

        add_draw_feature();

        //map.zoomToMaxExtent();
         map.setCenter(new OpenLayers.LonLat(6.325, 49.844 ), 1);

        $('.search_observation').trigger('click',  ['POLYGON((6.123334493632882 49.48921108228774,6.122647848125205 49.438782737864436,6.320401754347619 49.441015178027456,6.312162008255057 49.49233325498444,6.123334493632882 49.48921108228774))',
                                           "'polygon'"] );
    };

    /*-------------------------------------------------------------------------------*/
    /* switch between map drawing actions and normal map actions like zooming/moving */
    /*-------------------------------------------------------------------------------*/

    var toggleControl = function (element) {

        for(var key in drawControls) {
            if (drawControls.hasOwnProperty(key)) {
                var control = drawControls[key];
                if (element.value === key) {
                    control.activate();

                    EPSG_4326_geom = null;

                    removeObservationsLayer();
                }
                else {
                    control.deactivate();
                }
            }
        }
    };

    /*--------------------------------------------------------------*/
    /* push species observations in map as feature vectors (points) */
    /*--------------------------------------------------------------*/

    var addRecordsVectorLayers = function (data) {

        var myStyles = new OpenLayers.StyleMap({
            "default": new OpenLayers.Style( {
                pointRadius: "5", // sized according to type attribute
                fillColor: "#ffcc66",
                strokeColor: "#ff9933",
                strokeWidth: 2,
                graphicZIndex: 1,
                fillOpacity: 1
            }),
            "select": new OpenLayers.Style( {
                fillColor: "#ccff66",
                strokeColor: "#ff6600",
                graphicZIndex: 2,
                fillOpacity: 0.7,
                pointRadius: "10"
            })
        });

        featureLayer = new OpenLayers.Layer.Vector(
            'Observations',
            {
                styleMap: myStyles,
                rendererOptions: {zIndexing: true}
            }
        );

        map.addLayer(featureLayer);

        //species_name = data.species_details.item.title;

        var geometries = [];

        for (var x in data.result) {
            geometries.push(data.result[x].ol_geometry);
        }

        var features = [];

        for (var y in geometries) {
            var geom = eval(geometries[y]);

            var attributes = data.result[y];

            features.push(new OpenLayers.Feature.Vector (geom.transform(new OpenLayers.Projection("EPSG:4326"),
                                                         new OpenLayers.Projection("EPSG:900913")),
                                                         attributes));

            // assign the relation bewteen the observation id_record and vector_id > y
            point_obs_relation[data.result[y].id_record] = y;
        }

        featureLayer.addFeatures(features);
    };

    /*-------------------------------------------------------------------------------*/
    /* Highlight a point in the map when click on an observation in the result table */
    /*-------------------------------------------------------------------------------*/

    var highlight_point = function ( OpenLayers_Layer_Vector_ID ) {

        var style_map_obj = new OpenLayers.StyleMap();

        var symbolizer = false;

        highlight_flag = true;

        // when a point is already highlighted, we reset this point to its old style
        //
        if(highlighted_OpenLayers_Layer_Vector_ID !== false) {
            reset_highlighted_point()
        }

        highlighted_OpenLayers_Layer_Vector_ID = OpenLayers_Layer_Vector_ID;

        var observation_vector = featureLayer.features[point_obs_relation[OpenLayers_Layer_Vector_ID]];

        symbolizer = style_map_obj.createSymbolizer(observation_vector);

        symbolizer['fillColor'] = '#ccff66';
        symbolizer['strokeColor'] = '#ff6600';
        symbolizer['graphicZIndex'] = 2;
        symbolizer['fillOpacity'] = 0.7;
        symbolizer['pointRadius'] = 10;

        observation_vector.style = symbolizer;
        // redraw the feature with its new style
        observation_vector.layer.drawFeature(observation_vector);
    };

    /*-------------------------------------------------------------------------------*/
    /* Highlight a point in the map when click on an observation in the result table */
    /*-------------------------------------------------------------------------------*/

    var reset_highlighted_point = function () {

        var style_map_obj = new OpenLayers.StyleMap();

        var symbolizer = false;

        // when a point is already highlighted, we reset this point to its old style
        //
        if((highlighted_OpenLayers_Layer_Vector_ID !== false) && (point_obs_relation[highlighted_OpenLayers_Layer_Vector_ID])) {

            var highlighted_observation_vector = featureLayer.features[point_obs_relation[highlighted_OpenLayers_Layer_Vector_ID]];

            symbolizer = style_map_obj.createSymbolizer(highlighted_observation_vector);

            // apply the changes you want
            symbolizer['fillColor'] = '#ffcc66';
            symbolizer['strokeColor'] = '#ff9933';
            symbolizer['strokeWidth'] = 2;
            symbolizer['graphicZIndex'] = 1;
            symbolizer['fillOpacity'] = 1;
            symbolizer['pointRadius'] = 5;

            highlighted_observation_vector.style = symbolizer;
            // redraw the feature with its old style
            highlighted_observation_vector.layer.drawFeature(highlighted_observation_vector);

            highlighted_OpenLayers_Layer_Vector_ID = false;
        }
    };

    var resetHighlightedPoint = function () {
      reset_highlighted_point();
    };


    /*--------------------------------------------------------------------*/
    /* show species (taxonomic) details in the right column under the map */
    /*--------------------------------------------------------------------*/

    var showSpeciesDetails = function (data) {
        var list   = data.species_details.lists;
        var item   = data.species_details.item;
        var images = data.species_details.images;
        var files  = data.species_details.files;

        var result = '<div id="observation_info">';

        result = result + '<h2><span>' + data.species_details.item.title + '<\/span><\/h2>';

        result = result + '<table aria-live="assertive" id="taxon_attributes">';

        for (var a in item.attributes) {
            if (item.attributes[a].value !== null)
            {
                if (item.attributes[a].info.attribute_name === 'taxon_id')
                {
                    result = result + '<tr><td class="attribute_title">Info: <\/td><td><a href="http://www.catalogueoflife.org/details/species/id/' + item.attributes[a].value + '" target="_blank">Catalogue of Life<\/a><\/td><\/tr>';
                }
                else if((item.attributes[a].info.attribute_name === 'author') ||
                        (item.attributes[a].info.attribute_name === 'status') ||
                        (item.attributes[a].info.attribute_name === 'rank'))
                {
                    result = result + '<tr><td class="attribute_title">' + item.attributes[a].info.attribute_title + ': <\/td><td>' + item.attributes[a].value + '<\/td><\/tr>';
                }
            }
        }

        result     = result + '<\/table>';

        result = result + '<h3>Species lists:<\/h3>';

        result = result + '<table aria-live="assertive">';

        for (var a in list) {
            result = result + '<tr><td>' + list[a].branch.replace(/Taxonomy\/Plantae/,"");

            if (list[a].status)
            {
                result = result + '<ul>';
                for (var s in list[a].status)
                {
                    result = result + '<li>Status: <strong>' + list[a].status[s].title + '<\/strong><\/li>';
                }
                result = result + '<\/ul>';
            }

            result = result + '<\/td><\/tr>';
        }

        result     = result + '<\/table>';

        if (data.species_details.synonym) {
            var synonym = data.species_details.synonym;

            result = result + '<h3>Synonym of:<\/h3>';

            result = result + '<table aria-live="assertive">';

            for (a in synonym)
            {
                result = result + '<tr><td>' + synonym[a].branch.replace(/Taxonomy\/Plantae/,"") + '/' + synonym[a].item_title + '<\/td><\/tr>';
            }

            result     = result + '<\/table>';
        }

        /*** show item images ***/

        var is_image = 0;

        for (var i in images) {
            if (is_image === 0)
            {
                result = result + '<h3>Species images:<\/h3>';

                result = result + '<table aria-live="assertive">';

                is_image = 1;
            }

            result = result + '<tr><td><div class="floatbox">';

            result = result + '<div class="item_image"><a href="<?php echo $basePath; ?>/data/gc_item/' + data.species_details.item.files_folder + '/' + images[i].file_name + '" target="_blank"><img width="140" src="<?php echo $basePath; ?>/data/gc_item/' + data.species_details.item.files_folder + '/image/thumbnail/' + images[i].file_name + '" \/><\/a><\/div>';

            result = result + '<div class="item_image_description"><p>' + images[i].description + '<\/p><\/div>';

            result = result + '<\/div><\/td><\/tr>';
        }

        if (is_image === 1) {
            result = result + '<\/table>';
        }


        /*** show item files ***/

        var is_file = 0;

        for (var f in files) {
            if (is_file === 0)
            {
                result = result + '<h3>Species files:<\/h3>';

                result = result + '<table aria-live="assertive">';

                is_file = 1;
            }

            result = result + '<tr><td>';

            if (files[f].title === '')
            {
                result = result + '<div class="item_file"><a href="<?php echo $basePath; ?>/data/gc_item/' + data.species_details.item.files_folder + '/' + files[f].file_name + '" target="_blank">' + files[f].file_name + '<\/a><\/div>';
            }
            else
            {
                result = result + '<div class="item_file"><a href="<?php echo $basePath; ?>/data/gc_item/' + data.species_details.item.files_folder + '/' + files[f].file_name + '" target="_blank">' + files[f].title + '<\/a><\/div>';
            }

            result = result + '<div class="item_file_description"><p>' + files[f].description + '<\/p><\/div>';

            result = result + '<\/td><\/tr>';
        }

        if (is_file === 1) {
            result = result + '<\/table>';
        }

        result = result + '<\/div>';

        $('#result_right').hide();
        $('#result_right').html(result);
        $('#result_right').show('slow');
    };

    /*-------------------------------------*/
    /* transform meters in degrees (wgs84) */
    /*-------------------------------------*/

    var transformBufferSize = function ( buffer ) {
        if (buffer === 0) {
            return 0;
        }

        var source = new Proj4js.Proj('EPSG:900913');
        var dest   = new Proj4js.Proj('WGS84');

        /* get the centroid of the current map selection  */

        var source1       = new Proj4js.Point(selected_centroid.x +','+selected_centroid.y);
        var result1       = Proj4js.transform(source, dest, source1);
        var result_string = result1.toShortString();

        /*  extract the x value */

        var x_source1 = result_string.split(',');
        var x_value1  = parseFloat(x_source1[0]);


        /*  add buffer length to the current centroid point */

        var buffer_x = selected_centroid.x  + parseInt(buffer);
        var buffer_y = selected_centroid.y  + parseInt(buffer);

        /* transform the new point into wgs84  */

        var point2         = buffer_x + ',' + buffer_y;
        var source2        = new Proj4js.Point(point2);
        var result2        = Proj4js.transform(source, dest, source2);
        var result_string2 = result2.toShortString();

        /*  extract the x value */

        var x_source2 = result_string2.split(',');
        var x_value2  = parseFloat(x_source2[0]);

        /*  return the difference of the x values */

        return Math.abs(x_value2 - x_value1);
    };

    /*----------------------------------------*/
    /* remove observations layer from the map */
    /*----------------------------------------*/

    var removeObservationsLayer = function () {
        if (featureLayer !== null) {
           if (map.getLayer(featureLayer.id) !== null)
           {
              map.removeLayer(featureLayer);
           }
        }
    };

    /*---------------------------------------------------*/
    /* Show results in the left column in the result tab */
    /*---------------------------------------------------*/

    var showResult = function ( $data ) {

        if ($("#result_left").is(':visible')) {
            $("#result_left").animate({
              opacity: 0
            }, 200, "linear",
            function () {
                $("#result_left").html($data);
                $("#result_left").animate({
                  opacity: 1
                }, 600 );
            });
        }
        else if ($("#result_left").is(':hidden')) {
            $('#result_left').html($data);
            $('#result_left').show('slow');
            $('#result_left').attr("aria-live", "assertive");
        }

    };

    var showMessage = function ( $message ) {
       $('#result_left').show();
       $('#result_left').addClass('result_message');
       $('#result_left').html($message);
       $('#result_left').attr("aria-live", "assertive");

    };

    /*------------------------------------------------*/
    /* Show results in the right column under the map */
    /*------------------------------------------------*/

    var hideRightColumn = function () {
       $('#result_left').hide();
       $('#result_left').attr("aria-live", "off");
       $('#result_right').hide('slow');
    };

    var showRightColumn = function () {
       $('#result_left').show();
       $('#result_left').attr("aria-live", "assertive");
       $('#result_right').show();
    };

    /*-------------------------------------------*/
    /* if an ajax call was made set this to true */
    /*-------------------------------------------*/

    var running_action = function ( flag ) {
       running_action = flag;
    };

    /*------------------------------------------------------------------------*/
    /* enable some disabled menu actions and set running action flag to false */
    /*------------------------------------------------------------------------*/

    var release_action = function () {
       running_action = false;
    };

    /*-----------------------------------------------*/
    /* public methods and properties of geocontexter */
    /*-----------------------------------------------*/
    return {
        init                      : openlayers_init,
        toggleControl             : toggleControl,
        showRightColumn           : showRightColumn,
        hideRightColumn           : hideRightColumn,
        showResult                : showResult,
        showMessage               : showMessage,
        addRecordsVectorLayers    : addRecordsVectorLayers,
        removeObservationsLayer   : removeObservationsLayer,
        showSpeciesDetails        : showSpeciesDetails,
        transformBufferSize       : transformBufferSize,
        desactivateDrawControl    : desactivateDrawControl,
        EPSG_4326_geom_string     : function () {return EPSG_4326_geom_string;},
        EPSG_4326_geom            : function () {return EPSG_4326_geom;},
        geometry_type             : function () {return geometry_type;},
        is_running_action         : function () {return running_action;},
        get_species_name          : function () {return species_name;},
        running_action            : running_action,
        release_action            : release_action,
        highlight_point           : highlight_point,
        resetHighlightedPoint     : resetHighlightedPoint
    };
}();

</script>


<script type="text/javascript">

/*--------------------------*/
/* jquery + jquery-ui logic */
/*--------------------------*/

var gc_jquery = {

  id_project : '1000000000000001',

  model :
      function (obj, callback) {

          var _this = this;

          if(!obj.data.id_project) {
            obj.data.id_project = this.id_project;
          }

          $.ajax({
            type : "POST",
            url  : '<?php echo $basePath; ?>' + '/' + obj.controller,
            data : (obj.data),
            success: function (data) {
                callback(data);
            },
            error: function (data) {
                _this.ajaxError(data);
            }
        });
    },
    /**
     * Set configuration var
     *
     * @param string key var name  - required
     * @param mixed val  var value - required
     * @param bool writeable default = true
     */
    ajaxError :
        function (err) {
            if (typeof console.log === 'function') {
                console.log(this.dump(err));
            } else {
                alert(this.dump(err));
            }
        },
    /**
     * Return the config object as string
     * Needs at least ecma-262 5th
     */
    dump :
        function (param) {
            if (typeof JSON.stringify === 'function') {
                return JSON.stringify(param);
            } else {
                throw ({"type": 'warning', "val": 'function "dump" isnt supported by this browser'});
            }
        }
};

$(document).ready(function () {

//console.log(JSON.stringify(data));

    var tab_counter = 4;
    var new_panel   = false;
    var open_observation_tab = false;

    var_id_item       = false;
    var buffer        = false;
    var date_from     = false;
    var date_to       = false;
    var degree_buffer = false;
    var data = false;

    /**
     * Callback function which is activared after a search run for the first time
     * Called in jquery $('.search_observation')
     */
    var show_taxa_result_first_page = function(data) {
    
      geocontexter.addRecordsVectorLayers(data);
      _data = build_grid_data(data.result );

      // init jqGrid
      setGrid();

      // push data in grid
      for(var i=0;i<_data.length;i++) $("#list3").jqGrid('addRowData',_data[i].id_record,_data[i]);
      $("#list3").sortGrid("date_record_start");
      
      
		     var _class;
		     for (var a in _images) { 
			//console.log(_images[a]);
			_rel = "i"+_images[a];
			_class='.i'+_images[a];

			$(_class).colorbox({rel:_rel});
		     }
      
      
    };


    /*--------------------------------------------------------------------------------------------*/
    /* Search for observations - this functions is indirectly triggered by draw feature callbacks */
    /*--------------------------------------------------------------------------------------------*/

    $('.search_observation').bind('click', function (event, geom, type) {


        /* get checked keywords */
        var species_status_keyword_id_Array = [];



        /* prepare data object for ajax call */
        var model_data = {
          data : {
            //geom         : geom,
            page         : 1,
            buffer       : 0,
            id_keyword   : species_status_keyword_id_Array,
            alpha_filter : ''
          },
          controller: 'ajax-search-record-json'
        };

        /* run ajax request and pass the callback function "show_first_result" which handels the result */
        gc_jquery.model (model_data, show_taxa_result_first_page);
    });


var _images = [];
var _x = 0;

    function setGrid(){
      $("#list3").jqGrid(
        {
          datatype: "clientSide",
          autowidth: true,
          scrollrows: true,
          height: "auto",
          pager: '#ptoolbar',
          rowNum: 5,
          hidegrid: false,
          colNames:['Taxon','Date','Latitude/Longitude','Photo'],
          colModel:[
            {name:'taxon',index:'taxon', width:80, sortable:true, editable: false},
            {name:'date_record_start',index:'date_record_start', width:25, sortable:true, firstsortorder: 'desc'},
            {name:'latlong',index:'latlong', width:65, sortable:false, editable: false},
            {
                name: 'image',
                width: 80,
                fixed: true
            },
            ],
              viewrecords: true,
              caption: geocontexter.get_species_name(),
             onSelectRow: function(id){
                geocontexter.highlight_point(id);
             },
             onPaging: function(pgButton){

             },
             gridComplete: function(){   
                     
		     

		    
             },
         });

         $("#list3").jqGrid('bindKeys', {} );
       };

var _rel = false;

    function build_grid_data( data ) {
    
        var grid_data       = [];
        var __class_counter = 0;

        for (var a in data) {
            var tmp = {};

            tmp.id_record=data[a].id_record;
            tmp.date_record_start=data[a].date_record_start.replace(/[^ ]*$/,'');
            tmp.taxon=data[a].item.value;
            //tmp.taxon_status=data[a].item_attribute.value.name_status.value;
            //tmp.owner=data[a].owner.value;
            //tmp.num_ob=data[a].attributes.count.value + ' ' + data[a].attributes.count_acuracy.value;
            //tmp.project=data[a].project.value;

            var geom      = eval(data[a].ol_geometry); // = new OpenLayers.Geometry.Point(longitude,latitude)
            var latitude  = geom.y;
            var longitude = geom.x;

            tmp.latlong   = latitude.toFixed(6) + ' ' + longitude.toFixed(6);
            

            
            tmp.image         = '';
            var __class_group = 0;
            var __class       = '';
            
            /* push image tags of a record */
            
            for (var i in data[a].image) {

              /* only the first image tag of a record is visible */
              /* we need to include all images of a record > for the colorbox plugin */
              tmp.image = tmp.image + "<a class='cboxElement i" + __class_counter + __class + "' href='data/gc_record/" + data[a].id_record + "_" + data[a].media_folder_hash + "/image/" + data[a].image[i].media.file_name + "'><img src='data/gc_record/" + data[a].id_record + "_" + data[a].media_folder_hash + "/image/thumbnail/" + data[a].image[i].media.file_name + "' width='80' alt='my image' /></a>";           
	      
	      if (__class_group == 0) {
	      
	          /* this array is needed for the colorbox plugin */
		  _images.push(__class_counter);
		  
		  __class_group = 1;
		  __class       = ' i-hidden';
	      }
	      
            }
            
            grid_data.push(tmp);
            
            __class_counter = __class_counter + 1;
        }

        return grid_data;
    };



});




</script>


</head>

<body onload='geocontexter.init()'>

<?php echo $this->partial('layout/_navigation.phtml',
                          $partialData); ?>

<main>
    <div class="ym-wrapper">
        <div class="ym-wbox">


            <section class="ym-grid linearize-level-1">
                <article class="ym-g66 ym-gl content">
                    <div class="ym-gbox-left ym-clearfix">
                       <div id="map" class="smallmap olMap" role="region"></div>
                       <table id="list3" styles="width: 100%"></table>
                       <div id="ptoolbar" ></div>

                       <div class="search_observation"></div>

                    </div>
                </article>
                <aside class="ym-g33 ym-gr">
                    <div class="ym-gbox-right ym-clearfix">
                        <p>YouObserve ist ein Pilotprojekt dessen Zweck es ist
                           eine Plattform für Naturbeobachtungen zu entwickeln. </p>
                           <p>&nbsp;</p>
                           <p>&nbsp;</p>

                           <p>&nbsp;</p>
                           <p>&nbsp;</p>

                           <p>&nbsp;</p>
                           <p>__________________________________</p>
                           <p><strong>&lt;&lt;&lt;</strong> Neusten Beobachtungen. Ein Klick auf eine Tabellencollumne hebt
                              den Beobachtungespunkt in der Karte hervor. Bei sensibelen Arten wurde die geografische Referenz
                              auf 3 Stellen hinter dem Komma gekürzt.</p>


                    </div>
                </aside>
            </section>
        </div>
    </div>
</main>

<?php echo $this->partial('layout/_footer.phtml',
                          $partialData); ?>

</body>
</html>
